# -*- coding: utf-8 -*-
# @Author Ives
# @Date 2023/12/12 18:12
# @Version : 1.0.0
# @Contact : rszhang@bao.ac.cn
# @License : Copyright (C), 2023 NAOC
# @Desc : Write Coordinated Universal Time plus seconds to a txt file.

import datetime
from datetime import datetime, timedelta
import sys, os


def configpath():
    """
    返回文件存储路径
    """
    return os.path.dirname(os.path.realpath(__file__))


def add_seconds(time_str: str, sec: int):
    assert "T" in time_str, "Invalid datetime format. Expected format: YYYY-MM-DDTHH:MM:SS[.fff]"
    # 将UTC时间字符串转换为datetime对象，包括毫秒处理
    utc_time = datetime.strptime(time_str, "%Y-%m-%dT%H:%M:%S.%f" if '.' in time_str else "%Y-%m-%dT%H:%M:%S")

    # 添加秒数
    new_time = utc_time + timedelta(seconds=sec)

    # 将新的时间转换回字符串，包括毫秒
    new_time_str = new_time.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3]

    return new_time_str


if __name__ == '__main__':
    if len(sys.argv) < 3:
        print("Usage: script.py <UTC Time String> <Seconds>")
        sys.exit(1)

    try:
        file_name = "ut_time.txt"
        utc_time_str = sys.argv[1]
        seconds = int(sys.argv[2])
        output_time_str = add_seconds(utc_time_str, seconds)
        print(output_time_str)
        with open(os.path.join(configpath(), file_name), "w") as f:
            f.write("input_date_time     output_date_time       seconds\n")
            write_str = f"{utc_time_str}   {output_time_str}   {seconds}"
            f.write(write_str)
    except ValueError as e:
        print(f"Error: {e}")
